package com.film.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

import com.film.dao.SearchFilmDao;
import com.film.domain.Film;
import com.film.rowMapper.FilmRowMapper;
import com.film.util.DBUtil;


public class SearchFilmDaoImpl implements SearchFilmDao {
	private JdbcTemplate temp = new JdbcTemplate(DBUtil.getDataScorse());
	@Override
	public List<Film> searchFilms(String condition) {
		List<Film> films = new ArrayList<>();
		List<String> conditions = new ArrayList();
			for(int i = 0;i<4;i++) {
				conditions.add('%'+condition+'%');
			}
			if(condition == null || "".equals(condition) ) {
				String sql = "select * from film";
				return temp.query(sql, new FilmRowMapper());
			}else {
				Connection conn = null;
				PreparedStatement pre = null;
				ResultSet res = null;
				
				try {
					conn = DBUtil.getConnecion();
					String sql = "select DISTINCT t1.* from film t1 ,film_type t2 ,filmtype t3,film_performer t4 ,performer t5,film_director t6,director t7 WHERE t1.film_id = t2.film_id	and t3.type_id = t2.type_id and t1.film_id = t4.film_id and t4.per_id = t5.per_id and t1.film_id = t6.film_id and t7.dir_id = t6.dir_id and ((t1.film_name like ? or t3.type_name like ?) or (t5.per_name like ? or t7.dir_name like ?))"; 
					pre = conn.prepareStatement(sql);
					for(int i = 0;i<conditions.size();i++) {
						pre.setString(i+1,conditions.get(i));
					}
					res = pre.executeQuery();
				
				while(res.next()) {
					Film film = new Film();
					film.setFilmId(res.getInt("film_id"));
					film.setFilmName(res.getString("film_name"));
					film.setFilmForeignName(res.getString("film_foreignName"));
					film.setFilmPlace(res.getString("film_place"));
					film.setFilmTime(res.getString("film_time"));
					film.setFilmShowTime(res.getString("film_showTime"));
					film.setFilmImg(res.getString("film_img"));
					film.setIsDelete(res.getInt("is_delete"));
					film.setBoxoffice(res.getFloat("boxoffice"));
					film.setExpect(res.getInt("expect"));
					film.setFilmIunguage(res.getString("film_lunguage"));
					film.setFilmIntroduce(res.getString("film_introduce"));
					films.add(film);
					
				}
		
			}catch (Exception e) {
				
			}finally {
				DBUtil.closeAll(res, pre, conn);
			}
		}
		return films;
	}

}
